<template>
  <div class="page-wapper">
    <!-- 消息列表 -->
    <div class="container">
      <div class="tabs_warpper">
        <el-tabs v-model="currentTaskStatus" @tab-click="onTabClick">
          <el-tab-pane
            v-for="item in taskStatus"
            :key="item.status"
            :label="`${item.title}`"
            :name="item.status"
          ></el-tab-pane>
        </el-tabs>
        <div class="control_box">
          <el-button
            :type="isAllChecked ? 'warning' : 'primary'"
            size="mini"
            @click="toggleCheckAll"
          >
            {{ isAllChecked ? "取消全选" : "全选" }}
          </el-button>
          <el-button
            v-if="currentTaskStatus === '1'"
            type="success"
            size="mini"
            @click="setCheckHasRead"
          >
            标为已读
          </el-button>
          <el-button
            v-if="currentTaskStatus === '2'"
            type="danger"
            size="mini"
            @click="batchdelete"
          >
            批量删除
          </el-button>
          <el-button
            v-if="currentTaskStatus === '3'"
            type="warning"
            size="mini"
          >
            全部还原
          </el-button>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          ref="xTable"
          align="center"
          :show-header="false"
          height="100%"
          border="inner"
          show-overflow="tooltip"
          highlight-hover-row
          highlight-current-row
          class="xTable"
          :checkbox-config="{ checkField: 'checked', trigger: 'row' }"
          :row-config="{ height: 55 }"
          @checkbox-change="changeTableCheck"
        >
          <vxe-column type="checkbox" width="42" fixed="left"></vxe-column>

          <vxe-column
            type="seq"
            title="序号"
            width="42"
            fixed="left"
          ></vxe-column>

          <vxe-column title="消息标题" align="left">
            <template #default="{ row }">
              <div>
                <span
                  class="message_title"
                  :class="{
                    color_blue: !row.isRead,
                  }"
                >
                  【{{ row.typeLabel }}】{{ row.title }}
                </span>
              </div>
            </template>
          </vxe-column>

          <vxe-column field="createdTime" title="创建时间" width="160">
            <template #default="{ row }">
              <span style="font-weight: 600">
                {{ row.createdTime }}
              </span>
            </template>
          </vxe-column>

          <vxe-column #default="{ row }" width="110" title="操作">
            <div
              @click.stop=""
              style="display: flex; justify-content: flex-end"
            >
              <el-button
                v-if="currentTaskStatus === '1'"
                size="mini"
                @click="handleRead(row)"
              >
                标为已读
              </el-button>
              <el-button
                v-if="currentTaskStatus === '2'"
                type="danger"
                size="mini"
                plain
                @click="deleteTableDataMethod(row)"
              >
                删除
              </el-button>
              <el-button
                v-if="currentTaskStatus === '3'"
                type="warning"
                size="mini"
                plain
              >
                还原
              </el-button>
            </div>
          </vxe-column>
        </vxe-table>
      </div>
      <el-pagination
        v-model="pagenationData.current"
        :page-sizes="[500, 100, 50, 15]"
        :page-size="pagenationData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagenationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        style="text-align: center; margin-top: 10px"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import {
  ref,
  reactive,
  getCurrentInstance,
  onActivated,
  onBeforeUnmount,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import bus from "../../utils/bus";

const initFilterData = () => {
  return {
    isRead: false,
  };
};

export default {
  name: "MessageTable",
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const store = useStore();

    const currentTaskStatus = ref("1");
    const taskStatus = reactive([
      {
        title: "未读消息",
        status: "1",
        count: 0,
      },
      {
        title: "已读消息",
        status: "2",
        count: 0,
      },
      // {
      //   title: "回收站",
      //   status: "3",
      //   count: 0,
      // },
    ]);
    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});
    const xTable = ref(null);
    const tableData = ref([]);
    const tableLoading = ref(false);
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    const isAllChecked = ref(false);

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      tableLoading.value = true;
      $api.message
        .listPageSelf({
          ...pagenationData,
          condition,
        })
        .then((res) => {
          tableLoading.value = false;
          tableData.value = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
            };
          });
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableLoading.value = false;
          console.error("tableData error: ", err);
        });
    };

    // 单个设置已读
    const handleRead = (row) => {
      setHasReadByIds([row.id]);
    };

    // 批量设置已读
    const setCheckHasRead = () => {
      if (!tableData.value.length) {
        return ElMessage.warning("列表没有数据");
      }
      const selectedList = tableData.value.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      const ids = selectedList.map((item) => item.id);
      setHasReadByIds(ids);
    };

    // 单个删除
    const deleteTableDataMethod = (row) => {
      ElMessageBox.confirm(
        `确定要删除【${
          row.title.length > 10 ? row.title.slice(0, 10) + "..." : row.title
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          removeByIds([row.id]);
        })
        .catch(() => {});
    };

    // 批量删除
    const batchdelete = () => {
      if (!tableData.value.length) {
        return ElMessage.warning("列表没有数据");
      }
      const selectedList = tableData.value.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      ElMessageBox.confirm(
        `确定要删除 ${selectedList.length} 条数据吗？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          const ids = selectedList.map((item) => item.id);
          removeByIds(ids);
        })
        .catch(() => {});
    };

    // 批量设置消息已读接口
    const setHasReadByIds = (ids) => {
      tableLoading.value = true;
      $api.message
        .setHasReadByIds({
          ids,
        })
        .then((res) => {
          ElMessage.success("操作成功！");
          store.dispatch("message/getUnReadCount");
          isAllChecked.value = false;
          getTableData();
        })
        .catch((err) => {
          console.error("setHasReadByIds error: ", err);
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 删除内容接口
    const removeByIds = (ids) => {
      tableLoading.value = true;
      $api.message
        .removeByIds({
          ids,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          isAllChecked.value = false;
          getTableData();
        })
        .catch((err) => {
          console.error("removeByIds error: ", err);
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 点击标签
    const onTabClick = () => {
      // 清空勾选框
      switch (currentTaskStatus.value) {
        case "1":
          filterData.isRead = false;
          break;
        case "2":
          filterData.isRead = true;
          break;
      }
      pagenationData.current = 1;
      handleSearch();
      isAllChecked.value = false;
    };

    // 动态设置单元行样式
    const rowStyle = ({ rowIndex }) => {
      if (tableData.value[rowIndex].checked) {
        return {
          backgroundColor: "pink",
          // backgroundColor: 'lightblue',
          // color: '#ffffff'
        };
      }
    };

    const changeTableCheck = () => {
      isAllChecked.value = tableData.value.every((item) => item.checked);
    };

    const toggleCheckAll = () => {
      if (isAllChecked.value) {
        tableData.value.forEach((item) => {
          item.checked = false;
        });
        isAllChecked.value = false;
      } else {
        tableData.value.forEach((item) => {
          item.checked = true;
        });
        isAllChecked.value = true;
      }
    };

    /**
     * 初始化
     */
    bus.on("messageTableHandleSearch", handleSearch);

    onBeforeUnmount(() => {
      bus.off("messageTableHandleSearch", handleSearch);
    });

    onActivated(() => {
      handleSearch();
    });

    return {
      taskStatus,
      currentTaskStatus,
      xTable,
      tableData,
      tableLoading,
      pagenationData,
      handleRead,
      deleteTableDataMethod,
      batchdelete,
      rowStyle,
      onTabClick,
      handleSizeChange,
      handleCurrentChange,
      getTableData,
      setCheckHasRead,
      toggleCheckAll,
      changeTableCheck,
      isAllChecked,
    };
  },
};
</script>

<style lang="less" scoped>
.message_title {
  cursor: pointer;
}
.color_blue {
  color: #20a0ff;
}
.handle-row {
  margin-top: 30px;
}

.tabs_warpper {
  position: relative;
  .control_box {
    position: absolute;
    right: 0;
    top: 5px;
    z-index: 10;
  }
}
</style>
